package chances.epg.navigator.tag;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import chances.epg.commons.utils.SpringWebUtils;
import chances.epg.commons.utils.URLUtils;
import chances.epg.config.BaseMvcConfig;


public class CurrentURLTag extends TagSupport {

	private static final long serialVersionUID = 6835449197245032456L;
	private String params;
	private String var;
	private boolean encode;
	private String excludeParams;
	private String host;

	@Override
	public int doEndTag() throws JspException {
		
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		if (StringUtils.isEmpty(host)) {
			BaseMvcConfig  baseMvcConfig = SpringWebUtils.findBean(pageContext, BaseMvcConfig.class);
			host = baseMvcConfig.getEpgHost();
		}
		String aHost = 	host.replace( request.getContextPath(),"");
	
		String result = URLUtils.getCurrentPath(request, aHost, this.params, excludeParams);
		if (this.encode) {
			try {
				result = URLEncoder.encode(result, "UTF-8");
			} catch (UnsupportedEncodingException e) {
			}
		}
		pageContext.setAttribute(var, result);
		release();
		return super.doEndTag();
	}

	@Override
	public void release() {
		this.host = null;
		this.params = null;
		this.encode = false;
		this.var = null;
		this.excludeParams = null;
		super.release();
	}

	public String getParams() {
		return params;
	}

	public void setParams(String params) {
		this.params = params;
	}

	public String getVar() {
		return var;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public boolean isEncode() {
		return encode;
	}

	public void setEncode(boolean encode) {
		this.encode = encode;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getExcludeParams() {
		return excludeParams;
	}

	public void setExcludeParams(String excludeParams) {
		this.excludeParams = excludeParams;
	}
}
